package cn.gson.springboot.model.service.cusservice;

import cn.gson.springboot.model.dao.afterdao.*;
import cn.gson.springboot.model.dao.cusdao.*;
import cn.gson.springboot.model.dao.presaledao.*;
import cn.gson.springboot.model.dao.saledao.*;
import cn.gson.springboot.model.mapper.cusmapper.CulinkmanMapper;
import cn.gson.springboot.model.mapper.cusmapper.CustomerMapper;
import cn.gson.springboot.model.pjos.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional
@EnableTransactionManagement
public class CustomerService {
    Map<Object,String> map=new LinkedHashMap<>();
    @Autowired
    CustomerMapper customerMapper;//客户mapper
    @Autowired
    CulinkmanMapper culinkmanMapper;//联系人mapper
    @Autowired
    CustomerDao customerDao;//客户dao
    @Autowired
    CuclueDao cuclueDao;//线索dao
    @Autowired
    CulinkmanDao culinkmanDao;//联系人dao
    @Autowired
    ReceivingDao receivingDao;//客户地址dao
    @Autowired
    BusinessInfoDao businessInfoDao;//商机dao
    @Autowired
    ProgrammeDao programmeDao;//解决方案dao
    @Autowired
    OfferDao offerDao;//报价单dao
    @Autowired
    CompetitorDao competitorDao;//竞争对手dao
    @Autowired
    ContractDao contractDao;//合同dao
    @Autowired
    OrderInfoDao orderInfoDao;//订单
    @Autowired
    ReturnorderDao returnorderDao;//退货dao
    @Autowired
    CtschemesDao ctschemesDao;//回款dao
    @Autowired
    DeliveryplanDao deliveryplanDao;//交付计划dao
    @Autowired
    DemandDao demandDao;//客户需求dao
    @Autowired
    MaintainDao maintainDao;//维修dao
    @Autowired
    ComplainDao complainDao;//投诉dao
    @Autowired
    EvectionDao evectionDao;//出差dao
    @Autowired
    ServerDao serverDao;//客户服务dao
    @Autowired
    CustomerCareDao customerCareDao;//客户关怀dao
    @Autowired
    ExpenseDao expenseDao;//销售费用dao
    @Autowired
    MergeRecordDao mergeRecordDao;//合并记录dao
//    Customer customer=new Customer();

    //    分页查询我的客户
    public List<Customer> pageSelect(Integer empId,Integer deptId,String cusName,Integer typeId){
        return customerMapper.pageSelect(empId,deptId,1,1,cusName,typeId);
    }

    //    查询我关注的客户
    public List<Customer> selectAttention(Integer empId,Integer deptId,String cusName, Integer typeId){
        return customerMapper.selectAttention(empId,deptId,1,1,1,cusName,typeId);
    }

    //    选择客户时有效客户
    public List<Customer> haveType(String cusName){
        return customerMapper.haveType(4,1,cusName);
    }

//    设置关注
    public void updateAttention(Integer customId){
        Customer customer=customerDao.findById(customId).get();
        System.out.println("service关注："+customer);
        if(customer.getAttention()==1){
            customer.setAttention(0);//取消关注
        }else{
            customer.setAttention(1);//关注
        }
        customerDao.save(customer);
    }

    //    查询客户类型
    public List<CustomerType> selectCusType(){
        return customerMapper.selectCusType();
    }

    //    查询销售部员工
    public List<Emp> allEmp(String empName){
        return customerMapper.allEmp(3,15,1,empName);
    }

    //    修改客户负责人
    public void updateEmp(Integer[] customIdArr,Integer employeesId){
        for (int i=0;i<customIdArr.length;i++) {
            System.out.println(customIdArr[i]);
            Integer customId=customIdArr[i];
            customerMapper.updateEmp(employeesId,customId);
        }
    }

//    新增客户、联系人
    public void saveCustomer(Customer customer){
        CustomerType customerType=new CustomerType();
        customerType.setTypeId(1);
        System.out.println(customer.getCustomId());
        customer.setCusState(1);
        customer.setAttention(0);
        customer.setTypeId(customerType);//默认为潜在客户
//        修改客户
        if(customer.getCustomId()!=0){
            Customer customer1 = customerDao.findById(customer.getCustomId()).get();
            customer.setAttention(customer1.getAttention());//是否关注
            customer.setCustomTime(customer1.getCustomTime());//创建时间
        }
        customerDao.save(customer);
        //        一个客户有多个联系人，获取联系人集合
        customer.getCulinkmenByCustomId().forEach(link->{
            if(link.getCupName() != null){
                //            将联系人的客户id赋值为当前客户，循环赋值
                link.setCustomerByCustomId(customer);
                link.setCupState(1);
                link.setCupMaster(1);
//        多个联系人，批量添加
                culinkmanDao.saveAll(customer.getCulinkmenByCustomId());
            }
        });
    }

//    客户导入验证
    public String daoCustomer(String customer){
        JSONObject obj=(JSONObject)JSONObject.parse(customer);
        List customer1=obj.getObject("customer",List.class);
        JSONArray array = JSONArray.parseArray(String.valueOf(customer1));
        System.out.println(array);
        JSONObject object = null;
        JSONObject object2 = null;
        String err=null;
        for(int i=0;i<array.size();i++){
            object = (JSONObject) array.get(i);
            System.out.println("333:"+object.getString("empName"));
//            判断客户名称是否为空
            if(object.getString("cusName")!=null && object.getString("cusName")!="") {
                for (int j = 0; j < array.size(); j++) {
                    object2 = (JSONObject) array.get(j);
                    if (i != j) {
//                        判断Excel数据的客户名称是否有相同的名称
                        if (object.getString("cusName").equals(object2.getString("cusName"))) {
                            return err = "第" + (i + 1) + "行客户名与" + "第" + (j + 1) + "行客户名相同! 请重新输入!";
                        }
                    }
                }
                //   查询是否与数据库存在相同的客户名
                List<Customer> cus = customerMapper.selectCusName(object.getString("cusName"));
                if (cus.isEmpty() == false) {
//                如果有相同的客户名
                    return err = "第" + (i + 1) + "行客户名已经存在！请重新输入";
                }
                if (object.getString("cusSource") != null && object.getString("cusSource") != "") {
                    if (!object.getString("cusSource").equals("电话访问") && !object.getString("cusSource").equals("客户介绍") && !object.getString("cusSource").equals("其他路径")) {
                        return err = "第" + (i + 1) + "行客户来源格式有误！请重新输入";
                    }
                }else{

                }
                if (object.getInteger("attention") == 2) {
                    return err = "第" + (i + 1) + "行是否关注格式有误！请重新输入";
                }
                if (object.getString("cupName") == null || object.getString("cupName") == "") {
                    return err = "第" + (i + 1) + "行联系人为空！请输入后重试";
                }
                if(object.getString("cupPhone")==null || object.getString("cupPhone")==""){
                    return err="第"+(i+1)+"行联系电话为空！请输入后重试";
                }else{
                    String phoneReg = "^((13[0-9])|(14[0-9])|(15([0-9]))|(16[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
                    Pattern pattern = Pattern.compile(phoneReg);
                    Matcher matcher = pattern.matcher(object.getString("cupPhone"));
                    boolean isMatch = matcher.matches();
                    if(!isMatch){
                        return err="第"+(i+1)+"行联系电话格式错误！请重新输入";
                    }else{
                        for (int j = 0; j < array.size(); j++) {
                            object2 = (JSONObject) array.get(j);
                            if (i != j) {
//                        判断Excel数据的客户名称是否有相同的名称
                                if (object.getString("cupPhone").equals(object2.getString("cupPhone"))) {
                                    return err = "第" + (i + 1) + "行联系电话与" + "第" + (j + 1) + "行联系电话重复! 请重新输入!";
                                }else {
//                    查询是否与数据库有相同联系电话
                                    List<Culinkman> link = culinkmanMapper.selectCupPhone(object.getString("cupPhone"));
                                    if (link.isEmpty() == false) {
                                        //如果不为空，说明数据库存在该姓名
                                        return err = "第" + (i + 1) + "行联系人电话已存在！请输入后重试";
                                    }
                                }
                            }
                        }
                    }
                }
                if(object.getString("cupEmail")!=null && object.getString("cupEmail")!=""){
                    String regex = "(\\w{3,10}\\.)*\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}";
                    if(!object.getString("cupEmail").matches(regex)){
                        return err="第"+(i+1)+"行邮箱格式错误！请重新输入";
                    }
                }
                if(object.getString("empName")!=null && object.getString("empName")!=""){
                    //判断负责人是否存在
                    if(customerMapper.selectEmpNew(object.getString("empName"))==null){
                        return err="第"+(i+1)+"行负责人不存在！请输入后重试";
                    }
                }else{
                    System.out.println("3333:"+object.getString("empName"));
                    return err="第"+(i+1)+"行负责人为空！请输入后重试";
                }
            }else{
                return err="第"+(i+1)+"行客户名为空！请输入后重试";
            }
        }
        return err;
    }

    //处理
    public String addCustomerInfo(String customer){
        //客户验证
        String err = daoCustomer(customer);
        if(err!=null){
            return err;
        }else{
            Object o = JSONObject.toJSON(customer);
            JSONObject jsonx = JSON.parseObject(customer);
            JSONArray ja = jsonx.getJSONArray("customer");
            for(int index=0;index<ja.size();index++){
                JSONObject ob  = (JSONObject)ja.get(index);
                //客户新增
                addCustomer(ob);
            }
        }
        return "";
    }

    //新增客户（导入）
    public void addCustomer(JSONObject object){
        Customer customer2=new Customer();
        CustomerType customerType=new CustomerType();
        customerType.setTypeId(1);//潜在客户
        customer2.setCusName(object.getString("cusName"));
        customer2.setTypeId(customerType);
        customer2.setCusState(1);//有效客户
        customer2.setCusSource(object.getString("cusSource"));
        customer2.setAttention(object.getInteger("attention"));
        customer2.setCusAddressProvince(object.getString("cusAddressProvince"));
        customer2.setCusAddressCity(object.getString("cusAddressCity"));
        customer2.setCusAddressArea(object.getString("cusAddressArea"));
        customer2.setCusRemark(object.getString("cusRemark"));
//                负责人
        Emp emp=customerMapper.selectEmpNew(object.getString("empName"));
        customer2.setCustomEmpid(emp);
        customerDao.save(customer2);//添加客户
//        联系人
        Culinkman culinkman=new Culinkman();
        culinkman.setCupName(object.getString("cupName"));
        culinkman.setCupPhone(object.getString("cupPhone"));
        culinkman.setCupEmail(object.getString("cupEmail"));
        culinkman.setCupAddressProvince(object.getString("cupAddressProvince"));
        culinkman.setCupAddressCity(object.getString("cupAddressCity"));
        culinkman.setCupAddressArea(object.getString("cupAddressArea"));
        culinkman.setCupState(1);
        culinkman.setCupMaster(1);
        culinkman.setCustomerByCustomId(customer2);
        culinkmanDao.save(culinkman);
    }

    //    删除客户
    public String cusDel(Integer customId){
        String message=null;
//        查询该客户的商机
        List<BusinessInfo> business = customerMapper.selectBusiness(1,customId);
        System.out.println("business:"+business);
        if(business!=null && !business.isEmpty()){
            message="该客户已有商机，不予删除";
        }else {
            customerMapper.cusDel(4,customId);
        }
        return message;
    }

    //    查询客户姓名
    public List<Customer> selectCusName(String cusName){
        return customerMapper.selectCusName(cusName);
    }

    //    查询全部视图
    public List<Timeline> view(Integer customId){
        return customerMapper.view(customId);
    }

    //    根据客户id查询客户商机
    public List<BusinessInfo> selectBusiness(Integer customId){
        return customerMapper.selectBusiness(1,customId);
    }

    //    根据客户id查询客户合同
    public List<Contract> selectContract(Integer customId){
        return customerMapper.selectContract(1,customId);
    }

    //    根据客户id查询订单
    public List<OrderInfo> selectOrderInfo(Integer customId){
        return customerMapper.selectOrderInfo(customId);
    }

    //    根据客户ID查询回款
    public List<OrderInfo> selectCtschems(Integer customId){
        return customerMapper.selectCtschems(1,customId);
    }

    //    根据客户id查询客户关怀
    public List<CustomerCare> selectCustomerCare(Integer customId){
        return customerMapper.selectCustomerCare(1,customId);
    }

    //    根据客户ID查询交付记录
    public List<Deliverydetails> selectDeleveryDetails(Integer customId){
        return customerMapper.selectDeleveryDetails(1,customId);
    }

    //    根据客户ID查询维修单
    public List<Maintain> selectMaintain(Integer customId){
        return customerMapper.selectMaintain(1,customId);
    }

    //    根据客户id查询首要联系人
    public List<Culinkman> selectLinkman(Integer customId){
        return customerMapper.selectLinkman(1,customId);
    }

    //    根据客户ID查询客户、联系人
    public Customer customerLinkman(Integer customId){
        return customerMapper.customerLinkman(1,1,customId);
    }

//    客户合并
    public String merge(Integer congId, Integer daoId,Integer empId){
        System.out.println("congId:"+congId+"daoId:"+daoId);
        String error=null;
//        被合并客户（左侧客户）
        Customer customer1 = customerDao.findById(congId).get();
//        右侧客户
        Customer customer2 = customerDao.findById(daoId).get();
        System.out.println("客户：" + customer1);

        //        存储被合并客户的合并数据
        if(customer1!=null && customer2!=null){
            map.put("start","开始将"+" "+"“"+customer1.getCusName()+"”"+" "+"合并到"+" "+"“"+customer2.getCusName()+"”"+"，执行情况：");
        }

//        报价,4、5代表已完成
        for(int j=0;j<customer1.getOffersByCustomId().size();j++) {
            System.out.println("coming...报价"+customer1.getOffersByCustomId().get(j).getOfferStatus());
            if (customer1.getOffersByCustomId().get(j).getOfferStatus()<4) {
                System.err.println("报价是否完成："+customer1.getOffersByCustomId().get(j).getOfferStatus());
                return error = customer1.getOffersByCustomId().get(j).getOfferNumber() + "报价单未完成，不予合并！";
            }
        }
        if (error==null){
            System.out.println("error为空");
            //                    报价
            offerDao.updateCustomer(daoId, congId);
            if(customer1.getOffersByCustomId().size()!=0){
                map.put("offer"," 报价：共"+customer1.getOffersByCustomId().size()+"条数据，合并；");
            }
        }

        //        合同
        for (int k=0;k<customer1.getContractsByCustomId().size();k++){
            if (customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().size()!=0) {
//                循环订单
                for (int h = 0; h < customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().size(); h++) {
                    System.out.println("总金额：" + customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().get(h).getOrderTotal());
                    System.out.println("回款金额：" + customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().get(h).getReceivableOrder());
                    //            判断订单回款是否完成，如果未完成合同订单都不予合并
                    //            两个BigDecimal类型数据的比较，<，=，>的对应数值-1,0,1
                    if (customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().get(h).getOrderTotal().compareTo(customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().get(h).getReceivableOrder()) == 0) {
                        contractDao.upCustomer(daoId, congId);
                        //                回款
                        ctschemesDao.upCustomer(daoId, congId);
//                        订单
                        orderInfoDao.upDate(daoId,congId);
                    } else {
                        return error = customer1.getContractsByCustomId().get(k).getOrderInfosByContractId().get(h).getOrderName() + "订单回款未完成！不予合并";
                    }
                }
            }
        }

//        退货
        List<Returnorder> returnorders=returnorderDao.returnOrder(congId);
        returnorders.forEach(returnorder -> {
            returnorderDao.updateReturnOrder(daoId,congId);
        });

//        线索
        customer1.getCucluesByCustomId().forEach(cuclue -> {
            cuclueDao.upCustomer(daoId,congId);
            if(customer1.getCucluesByCustomId().size()!=0){
                map.put("cuclue"," 线索：共"+customer1.getCucluesByCustomId().size()+"条数据，合并；");
            }
        });
//        联系人合并
        customer2.getCulinkmenByCustomId().forEach(link2 -> {
            if (link2.getCupMaster() == 1) {
                customer1.getCulinkmenByCustomId().forEach(link1->{
                    link1.setCupMaster(0);
                    culinkmanDao.save(link1);
                });
            }
            culinkmanDao.upCustomer(daoId, congId);
            if(customer1.getCulinkmenByCustomId().size()!=0) {
                map.put("culinkman", " 联系人：共" + customer1.getCulinkmenByCustomId().size() + "条数据，合并；");
            }
        });
//        商机合并
        customer1.getBusinessInfosByCustomId().forEach(businessInfo -> {
            businessInfoDao.upsCustomer(daoId, congId);
            if(customer1.getBusinessInfosByCustomId().size()!=0){
                map.put("business"," 商机：共"+customer1.getBusinessInfosByCustomId().size()+"条数据，合并；");
            }
        });
//        竞争关系
        customer1.getCompetitorsByCustomId().forEach(competitor -> {
            competitorDao.uppCustomer(daoId, congId);
            if(customer1.getCompetitorsByCustomId().size()!=0){
                map.put("competitor"," 竞争关系：共"+customer1.getCompetitorsByCustomId().size()+"条数据，合并；");
            }
        });
//        解决方案
        customer1.getProgrammesByCustomId().forEach(programme -> {
            programmeDao.upCustomer(daoId, congId);
            if(customer1.getProgrammesByCustomId().size()!=0){
                map.put("programmer"," 解决方案：共"+customer1.getProgrammesByCustomId().size()+"条数据，合并；");
            }
        });
//        客户需求
        customer1.getDemandsByCustomId().forEach(demand -> {
            demandDao.update(daoId,congId);
            if (customer1.getDemandsByCustomId().size()!=0){
                map.put("demand"," 客户需求：共"+customer1.getDemandsByCustomId().size()+"条数据，合并；");
            }
        });

//        交付
        List<Deliveryplan> deliveryplanList=deliveryplanDao.selectDeliveryplan(congId);
        deliveryplanList.forEach(deliveryplan -> {
            deliveryplanDao.upCustomer(daoId,congId);
            if(deliveryplanList.size()!=0){
                map.put("deliveryplan"," 交付计划：共"+deliveryplanList.size()+"条数据，合并；");
            }
        });

//        维修
        customer1.getMaintainsByCustomId().forEach(maintain -> {
            maintainDao.update(daoId,congId);
            if(customer1.getMaintainsByCustomId().size()!=0){
                map.put("maintain"," 维修：共"+customer1.getMaintainsByCustomId().size()+"条数据，合并；");
            }
        });
//        投诉
        customer1.getComplainsByCustomId().forEach(complain -> {
            complainDao.update(daoId,congId);
            if(customer1.getComplainsByCustomId().size()!=0){
                map.put("complain"," 投诉：共"+customer1.getComplainsByCustomId().size()+"条数据，合并；");
            }
        });
//        出差
        customer1.getEvectionByCustomId().forEach(evection -> {
            evectionDao.update(daoId,congId);
            if (customer1.getEvectionByCustomId().size()!=0){
                map.put("evection"," 出差：共"+customer1.getEvectionByCustomId().size()+"条数据，合并；");
            }
        });
//        客户服务
        customer1.getServersByCustomId().forEach(server -> {
            serverDao.update(daoId,congId);
            if (customer1.getServersByCustomId().size()!=0){
                map.put("server"," 服务：共"+customer1.getServersByCustomId().size()+"条数据，合并；");
            }
        });
//        关怀
        List<CustomerCare> customerCareList=customerCareDao.selectCustomerCare(congId);
        customerCareList.forEach(customerCare -> {
            customerCareDao.update(daoId,congId);
            if(customerCareList.size()!=0){
                map.put("customercare"," 客户关怀：共"+customerCareList.size()+"条数据，合并；");
            }
        });
//        销售费用
        List<Expense> expenseList=expenseDao.selectExpense(congId);
        expenseList.forEach(expense -> {
            expenseDao.update(daoId,congId);
            if (expenseList.size()!=0){
                map.put("expense"," 销售费用：共"+expenseList.size()+"条数据，合并；");
            }
        });
//        逻辑删除左侧客户
        customerMapper.cusDel(4,congId);

//        新增合并记录表
        MergeRecord merge=new MergeRecord();
        merge.setMergeXixi("将客户： "+"“"+customer1.getCusName()+"”"+" 合并进入客户： "+"“"+customer2.getCusName()+"”");
        Emp emp = new Emp();
        emp.setEmployeesId(empId);
        merge.setEmpId(emp);
//        新增合并记录
        mergeRecordDao.save(merge);
//        如果有合同
        int OrderNum=0;//订单数量
        int ctsNum=0;//回款数量
        if (customer1.getContractsByCustomId().size()!=0) {
            map.put("contract", " 合同：共" + customer1.getContractsByCustomId().size() + "条数据，合并；");
//            循环客户合同
            for(int t=0;t<customer1.getContractsByCustomId().size();t++){
//                如果合同有订单
                if(customer1.getContractsByCustomId().get(t).getOrderInfosByContractId().size()!=0){
//                    循环订单
                    for (int p=0;p<customer1.getContractsByCustomId().get(t).getOrderInfosByContractId().size();p++){
                        OrderNum+=customer1.getContractsByCustomId().get(t).getOrderInfosByContractId().size();
                        map.put("orderInfo"," 订单：共"+OrderNum+"条数据，合并；");
//                        记录回款
                        if(customer1.getContractsByCustomId().get(t).getOrderInfosByContractId().get(p).getCtschemesByOrderId().size()!=0){
                            ctsNum+=customer1.getContractsByCustomId().get(t).getOrderInfosByContractId().get(p).getCtschemesByOrderId().size();
                            map.put("ctschemes"," 回款：共"+ctsNum+"条数据，合并；");
                        }
                    }
                }
            }
            System.out.println("合同数量："+customer1.getContractsByCustomId().size());
            System.out.println("订单数量："+OrderNum);
            System.out.println("回款数量："+ctsNum);
        }
        System.out.println("error:"+error);
        return error;
    }

//    合并成功，返回合并详细信息
    public Map<Object,String> map(){
        System.err.println("map:"+map);
        return map;
    }

    //    查询合并记录
    public List<MergeRecord> selectMerge(String startTime,String endTime){
        return customerMapper.selectMerge(startTime,endTime);
    }

    //    根据客户id查询客户地址
    public List<Receivingcontact> kehuAddress(Integer cusId){
        return customerMapper.kehuAddress(1,cusId);
    }

//    新增客户地址
    public void addAddress(Receivingcontact receivingcontact){
        receivingcontact.setRcState(1);//有效
        receivingDao.save(receivingcontact);
    }

//    删除客户地址
    public void delAddress(Receivingcontact receivingcontact){
        receivingDao.delete(receivingcontact);
    }

}
